package logic

import (
	"context"
	"strconv"
	"time"

	"probe-users/internal/errorx"
	"probe-users/internal/model"
	"probe-users/internal/svc"
	"probe-users/internal/utils"
	"probe-users/pb/users"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type CreateRoleLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateRoleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateRoleLogic {
	return &CreateRoleLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 角色管理接口
func (l *CreateRoleLogic) CreateRole(in *users.CreateRoleRequest) (*users.CreateRoleResponse, error) {
	// 参数验证
	if err := l.validate(in); err != nil {
		return nil, err
	}

	// 解析Token，获取当前用户角色
	claims, err := utils.ParseToken(in.Token, l.svcCtx.Config.JWTAuth.AccessSecret)
	if err != nil {
		return nil, err
	}

	// 检查权限：只有超级管理员（role_id=1）可以创建角色
	hasPermission, err := l.svcCtx.Enforcer.Enforce(strconv.FormatInt(claims.RoleId, 10), "role", "create")
	if err != nil {
		return nil, errors.Wrapf(err, "检查权限失败")
	}
	if !hasPermission {
		return nil, errorx.ErrPermissionDenied
	}

	// 检查角色名称是否已存在
	existingRole, err := l.svcCtx.RoleModel.FindByName(in.Name)
	if err != nil {
		return nil, errors.Wrapf(err, "查询角色失败: %s", in.Name)
	} else if existingRole != nil {
		return nil, errorx.ErrRoleNameExists
	}

	// 创建新角色
	now := time.Now()
	role := &model.Role{
		Name:      in.Name,
		Desc:      in.Desc,
		CreatedAt: now,
		UpdatedAt: now,
	}
	result, err := l.svcCtx.RoleModel.Insert(role)
	if err != nil {
		return nil, errors.Wrapf(err, "创建角色失败")
	}

	roleID, err := result.LastInsertId()
	if err != nil {
		return nil, errors.Wrapf(err, "获取角色ID失败")
	}

	return &users.CreateRoleResponse{
		Success: true,
		RoleId:  roleID,
	}, nil
}

func (l *CreateRoleLogic) validate(in *users.CreateRoleRequest) error {
	if in.Token == "" {
		return errorx.ErrTokenNotEmpty
	}
	if in.Name == "" {
		return errorx.ErrRoleNameNotEmpty
	}
	if len(in.Name) < 2 || len(in.Name) > 50 {
		return errorx.ErrRoleNameLengthInvalid
	}
	return nil
}
